package com.jingogo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jingogo.common.Result;
import com.jingogo.entity.Order;
import com.jingogo.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * 订单控制器
 *
 * @author jingogo
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/order")
@Tag(name = "订单管理", description = "订单相关接口")
@Validated
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping
    @Operation(summary = "创建订单", description = "创建商品订单")
    @PreAuthorize("hasRole('USER')")
    public Result<String> createOrder(@Valid @RequestBody Order order) {
        String orderId = orderService.createOrder(order);
        return Result.success("订单创建成功", orderId);
    }

    @PostMapping("/payment/callback")
    @Operation(summary = "支付回调", description = "第三方支付回调接口")
    public Result<String> paymentCallback(@RequestParam @NotBlank(message = "订单号不能为空") String orderNo,
                                        @RequestParam @NotBlank(message = "支付状态不能为空") String payStatus,
                                        @RequestParam(required = false) String payTime,
                                        @RequestParam(required = false) String transactionId) {
        orderService.handlePaymentCallback(orderNo, payStatus, payTime, transactionId);
        return Result.success("回调处理成功");
    }

    @PutMapping("/cancel/timeout")
    @Operation(summary = "超时取消订单", description = "定时任务调用，取消超时未支付订单")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> cancelTimeoutOrders() {
        int count = orderService.cancelTimeoutOrders();
        return Result.success("成功取消" + count + "个超时订单");
    }

    @GetMapping("/{orderNo}")
    @Operation(summary = "获取订单详情", description = "根据订单号获取订单详情")
    @PreAuthorize("hasRole('USER')")
    public Result<Order> getOrderDetail(@PathVariable @NotBlank(message = "订单号不能为空") String orderNo) {
        Order order = orderService.getOrderByNo(orderNo);
        return Result.success(order);
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "用户订单列表", description = "分页查询用户订单")
    @PreAuthorize("hasRole('USER')")
    public Result<IPage<Order>> getUserOrders(@PathVariable @NotNull(message = "用户ID不能为空") Long userId,
                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "10") Integer pageSize,
                                            @RequestParam(required = false) String status) {
        IPage<Order> orderPage = orderService.getUserOrders(userId, pageNum, pageSize, status);
        return Result.success(orderPage);
    }

    @PutMapping("/{orderNo}/status")
    @Operation(summary = "更新订单状态", description = "更新订单状态")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> updateOrderStatus(@PathVariable @NotBlank(message = "订单号不能为空") String orderNo,
                                          @RequestParam @NotBlank(message = "订单状态不能为空") String status) {
        orderService.updateOrderStatus(orderNo, status);
        return Result.success("订单状态更新成功");
    }

    @PostMapping("/{orderNo}/pay/wallet")
    @Operation(summary = "钱包支付", description = "使用钱包余额支付订单")
    @PreAuthorize("hasRole('USER')")
    public Result<String> payWithWallet(@PathVariable @NotBlank(message = "订单号不能为空") String orderNo,
                                      @RequestParam @NotNull(message = "用户ID不能为空") Long userId) {
        orderService.payWithWallet(orderNo, userId);
        return Result.success("订单支付成功");
    }
}